using System;
using CSScriptLibrary;
using System.Reflection;

namespace Core.Scripting
{
    public class ScriptLoader<T>
    {
        static ScriptLoader()
        {
            CSScript.AssemblyResolvingEnabled = true;
        }

        public static T LoadScript(string ScriptPath, string TypeToLoad, object[] args)
        {
            Assembly script = CSScript.Load(ScriptPath);

            return CreateInstance(script, TypeToLoad, args);
        }

        public static T LoadCode(string ScriptCode, string TypeToLoad, object[] args)
        {
            Assembly script = CSScript.LoadCode(ScriptCode, TypeToLoad, false);

            return CreateInstance(script, TypeToLoad, args);
        }

        protected static T CreateInstance(Assembly script, string TypeToLoad, object[] args)
        {
            T obj = (T)script.CreateInstance(TypeToLoad, true, BindingFlags.Default, null, args, null, null);

            return obj;
        }
    }
}
